package com.example.sort;

import org.apache.commons.beanutils.BeanComparator;
import org.apache.commons.collections.ComparatorUtils;
import org.apache.commons.collections.comparators.ComparableComparator;

import java.util.*;

/**
 * Created by SOAL on 2017/2/24 0024.
 */
public class MySort {
    public static void main(String[] args) {

        User user1 = new User();
        user1.setName("a");
        user1.setOrder(1);
        user1.setAge(11);
        User user2 = new User();
        user2.setName("b");
        user2.setOrder(2);
        user2.setAge(22);
        User user3 = new User();
        user3.setName("c");
        user3.setOrder(1);
        user3.setAge(12);
        List<User> list = new ArrayList<User>();
        //此处add user2再add user1
        list.add(user3); list.add(user1);list.add(user2);
//        Collections.sort(list);
//        for(User u : list){
//            System.out.println(u.getName());
//        }

        sort(list, "age", true);
        sort(list, "order", true);
        System.out.println(list);

    }

    public static <T> void sort(List<T> list, String property, boolean asc) {
        Comparator<?> comparator = ComparableComparator.getInstance();
        comparator = ComparatorUtils.nullLowComparator(comparator);
        if (!asc) {
            comparator = ComparatorUtils.reversedComparator(comparator);
        }
        Collections.sort(list, new BeanComparator(property, comparator));
    }
}
